#define  _GNU_SOURCE
#include <stdint.h>
#include <sys/types.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <signal.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include <stdio.h>
#include <pthread.h>
#include <poll.h>

/**
 *
 *  https://man7.org/linux/man-pages/man2/fcntl.2.html
 *
 */
void sigio_handler(int signum, siginfo_t *siginfo, void *act) {
	printf("sigio_handler:%d\n", signum);
}

void* run(void *ptr) {
	int flag ;
		struct sigaction act, oldact;
		sigemptyset(&act.sa_mask);
		sigaddset(&act.sa_mask, SIGIO);
		act.sa_flags = SA_SIGINFO;
		act.sa_sigaction = sigio_handler;
		if (sigaction(SIGIO, &act, &oldact) == -1) {
			goto fail;
		}

		int fd = open("/dev/t01", O_RDWR, O_NONBLOCK);
		if (fd < 0) {
			perror("open");
			printf("error open\n");
			goto fail;
		}

		if (fcntl(fd, F_SETOWN, getpid()) == -1) {
			goto fail;
		}

		if (fcntl(fd, F_SETSIG, SIGIO) == -1) {
			goto fail;
		}

		if ((flag = fcntl(fd, F_GETFL)) == -1) {
			goto fail;
		}

		if (fcntl(fd, F_SETFL, flag | FASYNC) == -1) {
			goto fail;
		}

		while(1){
			sleep(9999999);
		}
	return NULL;
	fail: printf("fail exit\n");
		return NULL;
}

int main() {
	pthread_t thread;
	pthread_create(&thread, NULL, run, NULL);
	pthread_join(thread, NULL);
	printf("main exit\n");
	return EXIT_SUCCESS;
}

